package com.ruoyi.part.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SerialNumberGenerator;
import com.ruoyi.part.domain.DmsPartStorageInfo;
import com.ruoyi.part.domain.DmsPartsDelivery;
import com.ruoyi.part.domain.DmsPartsPurchaseOrder;
import com.ruoyi.part.domain.DmsPartsPurchaseOrderDetail;
import com.ruoyi.part.mapper.DmsPartsDeliveryMapper;
import com.ruoyi.part.service.IDmsPartStorageInfoService;
import com.ruoyi.part.service.IDmsPartsDeliveryService;
import com.ruoyi.part.service.IDmsPartsPurchaseOrderDetailService;
import com.ruoyi.part.service.IDmsPartsPurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 零件发运Service业务层处理
 * 
 * @author liuchuanfa
 * @date 2024-03-17
 */
@Service
public class DmsPartsDeliveryServiceImpl extends ServiceImpl<DmsPartsDeliveryMapper,DmsPartsDelivery> implements IDmsPartsDeliveryService
{
    @Autowired
    private DmsPartsDeliveryMapper dmsPartsDeliveryMapper;
    @Autowired
    private IDmsPartsPurchaseOrderService iDmsPartsPurchaseOrderService;
    @Autowired
    private IDmsPartStorageInfoService iDmsPartStorageInfoService;
    @Autowired
    private IDmsPartsPurchaseOrderDetailService iDmsPartsPurchaseOrderDetailService;
    @Autowired
    SerialNumberGenerator serialNumberGenerator;

    /**
     * 查询零件发运
     * 
     * @param id 零件发运主键
     * @return 零件发运
     */
    @Override
    public DmsPartsDelivery selectDmsPartsDeliveryById(Long id)
    {
        return dmsPartsDeliveryMapper.selectDmsPartsDeliveryById(id);
    }

    /**
     * 查询零件发运列表
     * 
     * @param dmsPartsDelivery 零件发运
     * @return 零件发运
     */
    @Override
    public List<DmsPartsDelivery> selectDmsPartsDeliveryList(DmsPartsDelivery dmsPartsDelivery)
    {
        return dmsPartsDeliveryMapper.selectDmsPartsDeliveryList(dmsPartsDelivery);
    }

    /**
     * 新增零件发运
     * 
     * @param dmsPartsDelivery 零件发运
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDmsPartsDelivery(DmsPartsDelivery dmsPartsDelivery)
    {
        //新建发运订单时只能是已发运状态
        if (!dmsPartsDelivery.getDispatchStatus().equals(1)){
            throw new ServiceException("新建发运订单状态只能是已发运！");
        }

        //若没填写零件发运单号，则自动填充
        if (StrUtil.isBlank(dmsPartsDelivery.getDeliveryNo())){
            dmsPartsDelivery.setDeliveryNo(serialNumberGenerator.generateSerialNumber("LJFYDH"));
        }
        //填厂端id（经销商id签收的时候填）
        dmsPartsDelivery.setFactoryId(SecurityUtils.getLoginUser().getUser().getDept().getParentId());
        //填发运时间
        dmsPartsDelivery.setDispatchTime(new Date());

        //1. 修改采购订单状态为 待收货
        iDmsPartsPurchaseOrderService.lambdaUpdate()
                        .set(DmsPartsPurchaseOrder::getPurchaseStatus,6)
                                .eq(DmsPartsPurchaseOrder::getId,dmsPartsDelivery.getPurchaseId())
                                        .update();
        //2. 修改零件状态为 经销商在途
        //①根据采购订单号，查找零件id
        DmsPartsPurchaseOrderDetail dmsPartsPurchaseOrderDetail = new DmsPartsPurchaseOrderDetail();
        dmsPartsPurchaseOrderDetail.setPurchaseId(dmsPartsDelivery.getPurchaseId());
        List<DmsPartsPurchaseOrderDetail> dmsPartsPurchaseOrderDetails = iDmsPartsPurchaseOrderDetailService.selectDmsPartsPurchaseOrderDetailList(dmsPartsPurchaseOrderDetail);
        if (CollUtil.isEmpty(dmsPartsPurchaseOrderDetails)){
            throw new ServiceException("查询不到该采购订单下的零件号: "+ dmsPartsDelivery.getPurchaseId());
        }
        List<String> partNoList = dmsPartsPurchaseOrderDetails.stream().map(i -> i.getPartNo()).collect(Collectors.toList());
        //②修改零件状态
        iDmsPartStorageInfoService.lambdaUpdate()
                        .set(DmsPartStorageInfo::getPartStatus,1)
                                .in(DmsPartStorageInfo::getPartNo,partNoList)
                                        .update();

        save(dmsPartsDelivery);

        return 1;
    }

    /**
     * 修改零件发运
     * 
     * @param dmsPartsDelivery 零件发运
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDmsPartsDelivery(DmsPartsDelivery dmsPartsDelivery)
    {
        //状态不可逆
        DmsPartsDelivery dmsPartsDeliveryDB = selectDmsPartsDeliveryById(dmsPartsDelivery.getId());
        Integer statusDB = dmsPartsDeliveryDB.getDispatchStatus();
        Integer status = dmsPartsDelivery.getDispatchStatus();
        if (status-statusDB!=1){
            throw new ServiceException("状态不可逆 且 不可跨越！");
        }

        //发运订单状态为已签收时
        if (dmsPartsDelivery.getDispatchStatus().equals(3)){
            //0. 添加经销商id和经销商名称
            dmsPartsDelivery.setDealerId(SecurityUtils.getLoginUser().getUser().getUserId());
            dmsPartsDelivery.setDealerName(SecurityUtils.getLoginUser().getUser().getUserName());

            //1. 修改采购订单状态为已签收
            iDmsPartsPurchaseOrderService.lambdaUpdate()
                    .set(DmsPartsPurchaseOrder::getPurchaseStatus,7)
                    .eq(DmsPartsPurchaseOrder::getId,dmsPartsDelivery.getPurchaseId())
                    .update();

            //2. 修改零件状态为 经销商在库
            //①根据采购订单号，查找零件id
            DmsPartsPurchaseOrderDetail dmsPartsPurchaseOrderDetail = new DmsPartsPurchaseOrderDetail();
            dmsPartsPurchaseOrderDetail.setPurchaseId(dmsPartsDelivery.getPurchaseId());
            List<DmsPartsPurchaseOrderDetail> dmsPartsPurchaseOrderDetails = iDmsPartsPurchaseOrderDetailService.selectDmsPartsPurchaseOrderDetailList(dmsPartsPurchaseOrderDetail);
            if (CollUtil.isEmpty(dmsPartsPurchaseOrderDetails)){
                throw new ServiceException("查询不到该采购订单下的零件号: "+ dmsPartsDelivery.getPurchaseId());
            }
            List<String> partNoList = dmsPartsPurchaseOrderDetails.stream().map(i -> i.getPartNo()).collect(Collectors.toList());
            //②修改零件状态
            iDmsPartStorageInfoService.lambdaUpdate()
                    .set(DmsPartStorageInfo::getPartStatus,2)
                    .set(DmsPartStorageInfo::getDealerLastStorageTime,new Date())
                    .in(DmsPartStorageInfo::getPartNo,partNoList)
                    .update();
        }

        updateById(dmsPartsDelivery);
        return 1;
    }

    /**
     * 批量删除零件发运
     * 
     * @param ids 需要删除的零件发运主键
     * @return 结果
     */
    @Override
    public int deleteDmsPartsDeliveryByIds(Long[] ids)
    {
        return dmsPartsDeliveryMapper.deleteDmsPartsDeliveryByIds(ids);
    }

    /**
     * 删除零件发运信息
     * 
     * @param id 零件发运主键
     * @return 结果
     */
    @Override
    public int deleteDmsPartsDeliveryById(Long id)
    {
        return dmsPartsDeliveryMapper.deleteDmsPartsDeliveryById(id);
    }
}
